<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Token测试页面</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .test-section {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .test-section h3 {
            margin-top: 0;
            color: #333;
        }
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background: #0056b3;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .result {
            background: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 5px;
            padding: 10px;
            margin: 10px 0;
            white-space: pre-wrap;
            font-family: monospace;
            font-size: 12px;
        }
        .success {
            border-color: #28a745;
            background-color: #d4edda;
        }
        .error {
            border-color: #dc3545;
            background-color: #f8d7da;
        }
        input[type="text"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin: 5px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔧 Agent Boss Token测试工具</h1>
        
        <div class="test-section">
            <h3>1. Token状态检查</h3>
            <button onclick="checkTokenStatus()">检查当前Token状态</button>
            <button onclick="clearAllTokens()">清除所有Token</button>
            <button onclick="setNewToken()">设置新Token</button>
            <div id="tokenStatus" class="result"></div>
        </div>

        <div class="test-section">
            <h3>2. 手动Token设置</h3>
            <input type="text" id="manualToken" placeholder="输入JWT Token">
            <button onclick="setManualToken()">设置手动Token</button>
            <div id="manualTokenResult" class="result"></div>
        </div>

        <div class="test-section">
            <h3>3. API测试</h3>
            <button onclick="testDebugAPI()">测试调试接口</button>
            <button onclick="testChatAPI()">测试聊天接口</button>
            <button onclick="testWithRetry()">测试自动重试</button>
            <div id="apiTestResult" class="result"></div>
        </div>

        <div class="test-section">
            <h3>4. 消息测试</h3>
            <input type="text" id="testMessage" placeholder="输入测试消息" value="你好，请帮我查询Python工程师职位">
            <button onclick="sendTestMessage()">发送测试消息</button>
            <div id="messageTestResult" class="result"></div>
        </div>
    </div>

    <script>
        const API_BASE_URL = 'http://127.0.0.1:8000';
        const AGENT_BOSS_ENDPOINTS = {
            CHAT: '/agent_boss/chat/',
            DEBUG: '/agent_boss/debug/'
        };

        // 创建axios实例
        const apiClient = axios.create({
            baseURL: API_BASE_URL,
            timeout: 30000,
            headers: {
                'Content-Type': 'application/json',
            }
        });

        // 请求拦截器
        apiClient.interceptors.request.use(
            (config) => {
                const token = localStorage.getItem('access_token');
                if (token) {
                    if (token.startsWith('Bearer ')) {
                        config.headers.Authorization = token;
                    } else {
                        config.headers.Authorization = `Bearer ${token}`;
                    }
                }
                console.log('发送请求:', config.url, 'Token:', token ? token.substring(0, 20) + '...' : 'null');
                return config;
            },
            (error) => {
                console.error('请求错误:', error);
                return Promise.reject(error);
            }
        );

        // 响应拦截器
        apiClient.interceptors.response.use(
            (response) => {
                console.log('收到响应:', response.status, response.data);
                return response;
            },
            (error) => {
                console.error('响应错误:', error);
                return Promise.reject(error);
            }
        );

        function logResult(elementId, message, isSuccess = true) {
            const element = document.getElementById(elementId);
            element.textContent = message;
            element.className = `result ${isSuccess ? 'success' : 'error'}`;
        }

        function checkTokenStatus() {
            const token = localStorage.getItem('access_token');
            const userId = localStorage.getItem('userid');
            
            let status = 'Token状态检查:\n';
            status += `- access_token: ${token ? token.substring(0, 30) + '...' : 'null'}\n`;
            status += `- userid: ${userId || 'null'}\n`;
            status += `- Token长度: ${token ? token.length : 0}\n`;
            
            if (token) {
                try {
                    // 简单的JWT解析（不验证签名）
                    const parts = token.split('.');
                    if (parts.length === 3) {
                        const payload = JSON.parse(atob(parts[1]));
                        status += `- Token用户ID: ${payload.user_id}\n`;
                        status += `- Token过期时间: ${new Date(payload.exp * 1000).toLocaleString()}\n`;
                        status += `- Token是否过期: ${payload.exp * 1000 < Date.now() ? '是' : '否'}\n`;
                    }
                } catch (e) {
                    status += `- Token解析错误: ${e.message}\n`;
                }
            }
            
            logResult('tokenStatus', status, !!token);
        }

        function clearAllTokens() {
            localStorage.removeItem('access_token');
            localStorage.removeItem('userid');
            localStorage.removeItem('token');
            localStorage.removeItem('auth_token');
            localStorage.removeItem('jwt_token');
            logResult('tokenStatus', '所有Token已清除', true);
        }

        function setNewToken() {
            const newToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE3NjA5NTk3NTksImlhdCI6MTc2MDM1NDk1OX0.ykvGdf2I6X64LpgAMiqD-zOS2jmUccplrElpcWyyYEY';
            localStorage.setItem('access_token', newToken);
            localStorage.setItem('userid', '1');
            logResult('tokenStatus', '新Token已设置', true);
        }

        function setManualToken() {
            const token = document.getElementById('manualToken').value.trim();
            if (!token) {
                logResult('manualTokenResult', '请输入Token', false);
                return;
            }
            
            localStorage.setItem('access_token', token);
            localStorage.setItem('userid', '1');
            logResult('manualTokenResult', '手动Token已设置', true);
        }

        async function testDebugAPI() {
            try {
                const response = await apiClient.post(AGENT_BOSS_ENDPOINTS.DEBUG, {
                    test: 'token_verification'
                });
                logResult('apiTestResult', `调试接口测试成功:\n${JSON.stringify(response.data, null, 2)}`, true);
            } catch (error) {
                logResult('apiTestResult', `调试接口测试失败:\n${error.message}\n${error.response?.data ? JSON.stringify(error.response.data, null, 2) : ''}`, false);
            }
        }

        async function testChatAPI() {
            try {
                const response = await apiClient.post(AGENT_BOSS_ENDPOINTS.CHAT, {
                    question: 'test message',
                    session_id: 'test_session_' + Date.now()
                });
                logResult('apiTestResult', `聊天接口测试成功:\n${JSON.stringify(response.data, null, 2)}`, true);
            } catch (error) {
                logResult('apiTestResult', `聊天接口测试失败:\n${error.message}\n${error.response?.data ? JSON.stringify(error.response.data, null, 2) : ''}`, false);
            }
        }

        async function testWithRetry() {
            try {
                // 第一次尝试
                const response1 = await apiClient.post(AGENT_BOSS_ENDPOINTS.CHAT, {
                    question: 'retry test',
                    session_id: 'retry_test_session'
                });
                logResult('apiTestResult', `重试测试成功:\n${JSON.stringify(response1.data, null, 2)}`, true);
            } catch (error) {
                // 如果是认证错误，刷新Token后重试
                if (error.response?.data?.message?.includes('无效的Token') || 
                    error.response?.data?.message?.includes('认证失败')) {
                    
                    console.log('检测到认证错误，刷新Token后重试...');
                    setNewToken();
                    
                    try {
                        const retryResponse = await apiClient.post(AGENT_BOSS_ENDPOINTS.CHAT, {
                            question: 'retry test after token refresh',
                            session_id: 'retry_test_session_2'
                        });
                        logResult('apiTestResult', `重试测试成功（Token已刷新）:\n${JSON.stringify(retryResponse.data, null, 2)}`, true);
                    } catch (retryError) {
                        logResult('apiTestResult', `重试测试失败:\n${retryError.message}\n${retryError.response?.data ? JSON.stringify(retryError.response.data, null, 2) : ''}`, false);
                    }
                } else {
                    logResult('apiTestResult', `测试失败:\n${error.message}\n${error.response?.data ? JSON.stringify(error.response.data, null, 2) : ''}`, false);
                }
            }
        }

        async function sendTestMessage() {
            const message = document.getElementById('testMessage').value.trim();
            if (!message) {
                logResult('messageTestResult', '请输入测试消息', false);
                return;
            }

            try {
                const response = await apiClient.post(AGENT_BOSS_ENDPOINTS.CHAT, {
                    question: message,
                    session_id: 'test_message_session_' + Date.now()
                });
                
                let result = `消息发送成功:\n`;
                result += `问题: ${message}\n`;
                result += `回复: ${response.data.data?.response || '无回复内容'}\n`;
                result += `用户ID: ${response.data.data?.user_id}\n`;
                result += `会话ID: ${response.data.data?.session_id}`;
                
                logResult('messageTestResult', result, true);
            } catch (error) {
                let result = `消息发送失败:\n`;
                result += `问题: ${message}\n`;
                result += `错误: ${error.message}\n`;
                if (error.response?.data) {
                    result += `响应数据: ${JSON.stringify(error.response.data, null, 2)}`;
                }
                
                logResult('messageTestResult', result, false);
            }
        }

        // 页面加载时检查Token状态
        window.onload = function() {
            checkTokenStatus();
        };
    </script>
</body>
</html>
